package org.scohen.juploadr.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.scohen.juploadr.Messages;
import org.scohen.juploadr.prefs.Configuration;
import org.scohen.juploadr.ui.MessageUtils;
import org.scohen.juploadr.ui.ReusableUIFactory;

import edu.stanford.ejalbert.BrowserLauncher;
import edu.stanford.ejalbert.exception.BrowserLaunchingExecutionException;
import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException;
import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException;
import edu.stanford.ejalbert.exceptionhandler.BrowserLauncherErrorHandler;

/**
 * Opens a URL in the preferred web browser. This implementation prefers firefox
 * over all others.
 * 
 * @author steve
 */
public class JUploadrBrowserLauncher {
    private static BrowserLauncher launcher;

    static {
        try {
            launcher = new BrowserLauncher(null);
        } catch (BrowserLaunchingInitializingException e) {
        } catch (UnsupportedOperatingSystemException e) {
        }
    }

    public static void openURL(final String url) {
        openURL(url, Messages.getString("juploadr.browser.not.found"));
    }

    public static void openURL(final String url, final String message) {

        if (launcher != null && !Configuration.isMac()) {
            Thread t = new Thread() {
                public void run() {
                    launcher.openURLinBrowser(getFirefoxBrowser(launcher.getBrowserList()), url);
                }
            };
            ReusableUIFactory.getInstance().getDisplay().syncExec(t);
        } else if (Configuration.isMac()) {
            try {
                Runtime.getRuntime().exec("open " + url);
            } catch (IOException e) {
                handleNoBrowserAvailable(url, message);
            }
        } else {
            handleNoBrowserAvailable(url, message);
        }
    }

    private static String getFirefoxBrowser(List browsers) {
        if (browsers != null && browsers.size() > 0) {
            String browserName = (String) browsers.get(0);
            Iterator iter = browsers.iterator();
            while (iter.hasNext()) {
                String name = (String) iter.next();
                if ("Firefox".equalsIgnoreCase(name)) {
                    return name;
                }
            }
            return browserName;
        }
        return null;
    }

    private static void handleNoBrowserAvailable(String url, String message) {
        Clipboard clipboard = new Clipboard(ReusableUIFactory.getInstance().getDisplay());
        Transfer[] transfers = { TextTransfer.getInstance() };
        Object[] data = { url };
        clipboard.setContents(data, transfers);
        clipboard.dispose();
        MessageUtils.showErrorMessage(message);

    }

}
